<template>
  <div class="forum-container">
    <div class="header">
      <el-button type="primary" @click="handleAdd">发帖</el-button>
    </div>

    <el-card v-for="post in posts" :key="post.id" class="post-item">
      <template #header>
        <div class="post-header">
          <h3>{{ post.title }}</h3>
          <div class="post-info">
            <span>{{ post.username }}</span>
            <span class="time">{{ post.createTime }}</span>
          </div>
        </div>
      </template>
      <div class="post-content">{{ post.content }}</div>
      <div class="post-footer">
        <el-button link type="primary" @click="handleReply(post)">回复</el-button>
        <el-button v-if="isAdmin || post.userId === currentUserId" link type="danger" @click="handleDelete(post)">删除</el-button>
      </div>

      <!-- 回复列表 -->
      <div class="replies" v-if="post.replies && post.replies.length > 0">
        <div v-for="reply in post.replies" :key="reply.id" class="reply-item">
          <div class="reply-header">
            <span>{{ reply.username }}</span>
            <span class="time">{{ reply.createTime }}</span>
          </div>
          <div class="reply-content">{{ reply.content }}</div>
        </div>
      </div>
    </el-card>

    <el-pagination
      class="pagination"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 发帖对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'post' ? '发帖' : '回复'"
      width="50%"
    >
      <el-form :model="postForm" :rules="rules" ref="postFormRef">
        <el-form-item label="标题" prop="title" v-if="dialogType === 'post'">
          <el-input v-model="postForm.title" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="postForm.content" :rows="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request'

const posts = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('post')
const postFormRef = ref()
const postForm = ref({
  title: '',
  content: ''
})
const currentUserId = ref(1) // TODO: 从用户信息中获取
const isAdmin = ref(true) // TODO: 从用户信息中获取
const currentPost = ref(null)

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

const loadData = async () => {
  try {
    const res = await request.get('/api/forum/list', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    if (res.data.code === 200) {
      posts.value = res.data.data.records
      total.value = res.data.data.total
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const handleAdd = () => {
  dialogType.value = 'post'
  postForm.value = {
    title: '',
    content: ''
  }
  dialogVisible.value = true
}

const handleReply = (post) => {
  dialogType.value = 'reply'
  currentPost.value = post
  postForm.value = {
    content: ''
  }
  dialogVisible.value = true
}

const handleDelete = (post) => {
  ElMessageBox.confirm('确定要删除该帖子吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request.delete(`/api/forum/${post.id}`)
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        loadData()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = () => {
  postFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (dialogType.value === 'post') {
          res = await request.post('/api/forum', postForm.value)
        } else {
          res = await request.post(`/api/forum/${currentPost.value.id}/reply`, {
            content: postForm.value.content
          })
        }
        if (res.data.code === 200) {
          ElMessage.success(dialogType.value === 'post' ? '发帖成功' : '回复成功')
          dialogVisible.value = false
          loadData()
        }
      } catch (error) {
        ElMessage.error(dialogType.value === 'post' ? '发帖失败' : '回复失败')
      }
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.forum-container {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}
.post-item {
  margin-bottom: 20px;
}
.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.post-info {
  font-size: 14px;
  color: #999;
}
.time {
  margin-left: 10px;
}
.post-content {
  padding: 10px 0;
}
.post-footer {
  display: flex;
  justify-content: flex-end;
}
.replies {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}
.reply-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
.reply-header {
  font-size: 14px;
  margin-bottom: 5px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 